﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JSC.Core.Attributes;

namespace JSC.Core
{
    public static class FacadeFactory
    {
        static readonly SortedList<string, Type> _facades = new SortedList<string, Type>();
        public static T CreateFacade<T>()
        {
            if (_facades.ContainsKey(typeof(T).FullName))
            {
                return (T)Activator.CreateInstance(_facades[typeof(T).FullName]);
            }
            var attributes = typeof(T).GetCustomAttributes(typeof(ConcreteTypeAttribute), true);
            if (attributes.Length > 0 && attributes[0] is ConcreteTypeAttribute)
            {
                var facadeName = ((ConcreteTypeAttribute)attributes[0]).FullyQualifiedTypeName;
                var targetType = Type.GetType(facadeName);
                _facades[typeof(T).FullName] = targetType;
                return (T)Activator.CreateInstance(targetType);
            }
            return default(T);
        }
    }
}
